#ifndef __M_MYSQL_UTIL_HPP__
#define __M_MYSQL_UTIL_HPP__

#include "logger.hpp"
#include <mysql/mysql.h>
#include <string>
#include <jsoncpp/json/json.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <memory>
#include <mutex>

#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
class mysql_util
{
public:
    // 创建连接
    static MYSQL *mysql_create(const std::string &host,
                               const std::string &username,
                               const std::string &password,
                               const std::string &dbname,
                               const unsigned int port = 3306)
    {
        // 初始化句柄
        MYSQL *mysql = mysql_init(NULL); // 如果参数是NULL,那么就会自动在堆上空间
        if (mysql == NULL)
        {
            ELOG("mysql_init() failed\n");
            return NULL;
        }
        // 2.连接服务器 MYSQL* mysql_real_connect(mysql,host,user,pwd,dbname,port,unix_socket,flag);
        if (mysql_real_connect(mysql, host.c_str(), username.c_str(), password.c_str(), dbname.c_str(), port, NULL, 0) == NULL)
        {
            ELOG("mysql connect failed: %s \n", mysql_error(mysql));
            mysql_close(mysql);
            return NULL;
        }
        // 3.设置客户端字符集 int mysql_set_character_set
        if (mysql_set_character_set(mysql, "utf8") != 0)
        {
            ELOG("set character failed: %s \n", mysql_error(mysql));
            mysql_close(mysql);
            return NULL;
        }
        return mysql;
    }
    // 执行sql语句
    static bool mysql_exec(MYSQL *mysql, const std::string &sql)
    {
        int ret = mysql_query(mysql, sql.c_str());
        if (ret != 0)
        {
            ELOG("%s \n", sql.c_str());
            ELOG("query failed: %s \n", mysql_error(mysql));
            return false;
        }
        return true;
    }
    // 获取结果集
    static void mysql_destroy(MYSQL *mysql)
    {
        if (mysql != NULL)
        {
            mysql_close(mysql);
        }
    }
};

class json_util
{
public:
    static bool serialize(const Json::Value &root, std::string &str)
    {

        Json::StreamWriterBuilder builder;
        // 3.通过StreamWriterBuilder对象的newStreamWriter()方法,创建一个StreamWriter对象

        std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
        // 4.通过StreamWriter对象的write()方法,将Json::Value对象序列化为字符串
        std::stringstream ss;
        int ret = writer->write(root, &ss);
        if (ret != 0)
        {
            ELOG("json serialize error");
            return false;
        }
        str = ss.str();
        return true;
    }
    static bool unserialize(const std::string &json_str, Json::Value &root)
    {
        // unserialize是不是把字符串转为Json
         DLOG("json_str: %s",json_str.c_str());
        Json::CharReaderBuilder builder;
        std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
        std::string err;
        bool ret = reader->parse(json_str.c_str(), json_str.c_str() + json_str.size(), &root, &err);
        if (ret == false)
        {
            ELOG("json unserialize error %s", err.c_str());
            return false;
        }  
        return true;
    }
};

class string_util
{
public:
    // 将源字符根据sep进行分割,放在vector中返回
    static int split(const std::string &src, const std::string &sep, std::vector<std::string> &res)
    {
        // 123,4342,,,321
        size_t pos = 0, idx = 0;
        while (idx < src.size())
        {
            pos = src.find(sep, idx);
            if (pos == std::string::npos)
            {
                res.push_back(src.substr(idx));
                break;
            }
            // 如果分割符重复出现,就越过
            if(pos == idx)
            {
                idx += sep.size();
                continue;
            }
            res.push_back(src.substr(idx, pos - idx));
            idx = pos + sep.size();
        }
        return res.size();  
    }
};

class file_util
{
    public:
    // 将文件内容读到body中
    static bool read(const std::string &filename,std::string& body)
    {   
        // 1.打开文件
        std::ifstream file(filename.c_str(),std::ios::binary); // 以二进制打开
        if(!file.is_open())
        {
            ELOG("open file %s failed",filename.c_str());
            return false;
        }
        // 2. 获取文件大小
        size_t fsize = 0;
        file.seekg(0,std::ios::end); // 定位到文件末尾
        fsize = file.tellg(); // 获取文件大小
        file.seekg(0,std::ios::beg); // 定位到文件开头
        if(fsize <= 0)
        {
            ELOG("file %s is empty",filename.c_str());
            file.close();
            return false;
        }
        //3.读取文件内容
        body.resize(fsize);
        file.read(&body[0],fsize); // 读取文件内容到body中
        if(file.gcount() != fsize)
        {
            ELOG("read file %s failed",filename.c_str());
            file.close();
            return false;
        }
        // 4.关闭文件
        file.close();
        return true;
    }
};

#endif
